package handler

import (
	"context"
	"gluenet/pkg/apis"
	"gluenet/pkg/ops"
)

const EsLogMapping = `
{
  "mappings": {
    "properties": {
      "agent_guid": {
        "type": "text"
      },
      "application_guid": {
        "type": "text"
      },
      "container": {
        "type": "text"
      },
      "level": {
        "type": "keyword"
      },
      "message": {
        "type": "text"
      },
      "object": {
        "type": "text"
      },
      "organize": {
        "type": "text"
      },
      "platform": {
        "type": "text"
      },
      "stream": {
        "type": "text"
      },
      "structured": {
        "type": "text"
      },
      "timestamp": {
        "type": "long"
      }
    }
  }
}`

// EsLog structure of EsLog
type EsLog struct {
	AgentGuid       string `json:"agent_guid"`
	ApplicationGuid string `json:"application_guid"`
	Container       string `json:"container"`
	Level           string `json:"level"`
	Message         string `json:"message"`
	Object          string `json:"object"`
	Organize        string `json:"organize"`
	Platform        string `json:"platform"`
	Stream          string `json:"stream"`
	Structured      string `json:"structured"`
	Timestamp       int    `json:"timestamp"`
}

// Logs Push logs to ElasticSearch
func Logs(ctx *apis.StorageContext) {
	//Get client index
	client := ctx.DataBase.GetESClient()
	c := context.Background()
	//Check if es index exists, if not then create it
	exists, err := client.IndexExists(ops.EsLog).Do(c)
	if err != nil {
		ctx.Logger.Errorf("check es index failed " + err.Error())
	}
	if !exists {
		_, err := client.CreateIndex(ops.EsLog).BodyString(EsLogMapping).Do(c)
		if err != nil {
			ctx.Logger.Errorf("create es index failed ", err.Error())
		}
	}
	//Push logs to es
	_, err = client.Index().Index(ops.EsLog).BodyString(string(ctx.RpcContext.Data.Data)).Do(c)
	if err != nil {
		ctx.Logger.Errorf("push logs to es failed ", err.Error())
	}
}
